<template>
	<view class="image-list c-flex c-flex-wrap">
		<view class="img-l-item" v-for="(item,i) in imgUrls" :key="i" >
			<image class='img-item' :src='item' mode='aspectFill' @click="onPreview(item)"></image>
			<image class="remove" src="@/static/images/common/remove-icon.png" @click="onRemove(item)"></image>
		</view>
		<view class="capture-con c-flex c-flex-col jc-center c-item-center" @click="upload_image()">
			<image src="@/static/images/common/sm-capture-img.png" ></image>
			<view>添加照片</view>
		</view>
		<WaterMark ref="watermark"  :fontSize="40" :fontColor="'#ffffff'" :markAlign="'bottomLeft'" style="transform:translate(-9999px, 0px);"
								@waterMark="waterMarkFun"></WaterMark>
	</view>
</template>

<script>
	import {aliOssParams} from '@/utils/oss/oss.js';
	import {toast,getNowTime} from '@/utils/utils.js';
	import WaterMark from '@/components/waterMark/waterMark.vue';
	export default {
		name:"imageSelect",
		components:{WaterMark},
		data() {
			return {
				imglist:[],
				imgUrls:[],
				url: 'https://tyd-worksite.oss-cn-beijing.aliyuncs.com',
			};
		},
		props:{
			list:{
				type: Array,
				default: () => {
					return []
				}
			},
			sourceType:{
				type: Array,
				default: () => {
					return ['album', 'camera'];
				}
			},
			count:{
				type:Number,
				default:1
			}
		},
		watch:{
			list(newval){
				this.imgUrls = newval;
				console.log(newval)
			}
		},
		onReady() {
			
		},
		methods:{
			upload_image() {
				let that = this;
				uni.chooseImage({
					count: this.count, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: this.sourceType, //从相册选择
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						const tempFilePaths = res.tempFilePaths;
						that.imgList = res.tempFilePaths;
						console.log(that.imgList)
						for (let i = 0; i < tempFilePaths.length; i++) {
							that.getAccessInfo(tempFilePaths[i]);
						}
					}
				});
			},
			getAccessInfo(filePath) {
				this.$API.getAccessInfo().then(res => {
					if (res.code == 0) {
						var accessInfo = res.data;
						const {accessKeySecret,accessKeyId,expiration,securityToken} = accessInfo;
						var obj = aliOssParams(accessKeyId, accessKeySecret, expiration, securityToken, this.url,
							'png', 'image/tyd-worksite/gas/');
						if (obj) {
							this.uploadProgress(filePath, obj);
						} else {
							toast('数据错误，请重新上传');
						}
					}
			
				})
			},
			uploadProgress(filePath, obj) {
				let that = this;
				uni.showLoading({
					title: '上传中...',
					icon: 'none'
				})
			
				const uploadTask = uni.uploadFile({
					url: obj.host,
					filePath: filePath,
					name: 'file',
					formData: {
						'key': obj.fileName,
						'policy': obj.policy,
						'OSSAccessKeyId': obj.aid,
						'signature': obj.signature,
						'x-oss-security-token': obj.securityToken,
						'success_action_status': '200'
			
					},
					success: function(uploadFileRes) {
						console.log(uploadFileRes);
						if (uploadFileRes.statusCode == 200) {
							let imgUrl = that.url + '/' + obj.fileName;
							that.imgUrls.push(imgUrl)
							uni.hideLoading()
							toast('上传成功');
						} else {
							toast('上传失败');
							uni.hideLoading()
						}
			
					},
					fail(err) {
						console.log('error:', err);
						toast('上传失败');
						uni.hideLoading()
					}
				});
			},
			//添加图片
			onAddImage(){
				const that = this;
				uni.chooseImage({
					count: 1,  // 最多可以选择的图片张数，默认9
					sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
					success: function (res) {						
						// if (that.imglist.length === 0) {
						// 	that.imglist = res.tempFilePaths;
						// } else if (that.imglist.length < 11) {
						// 	that.imglist = that.imglist.concat(res.tempFilePaths); //concat追加到数组
						// }
						console.log(that.imglist)
						const location = uni.getStorageSync('local');
						const user = uni.getStorageSync('user');
						const tenantName = uni.getStorageSync('tenantName');
						const filePaths = res.tempFilePaths;
						var fillTexts = [];
						if(user){
							fillTexts.push("上传人员：" + user.username+'-'+user.title+'-'+tenantName);
						}
						if(location){
							fillTexts.push("上传地址：" + location.address);
							fillTexts.push("上传位置：" + location.gps);
						}
						fillTexts.push("上传时间：" + getNowTime());
						// 添加水印
						that.$refs.watermark.addWaterMark({filePaths,fillTexts});
						// that.onUploadImg(res.tempFilePaths[0]);
					}
				})
			},
			/**
			 * 水印添加回调，在H5平台下，filePath 为 base64
			 */
			waterMarkFun(filePath){
				this.imglist.push(filePath);
				this.onUploadImg(filePath)
					console.log('filepath',filePath)
			},
			//删除图片
			onRemove(item){
				console.log(item)
				const arr = this.imgUrls.filter(citem => {return citem != item });
				this.imgUrls = arr;
				console.log()
			},
			onPreview(url){
				uni.previewImage({
					urls: this.imgUrls,
					current: url,
					success: () => {},
					fail: () => {
						uni.showToast({
							title: '预览图片失败',
							icon: 'none'
						});
					}
				});
			},
			//上传图片
			onUploadImg(imgUrl){
				const token = wx.getStorageSync('token');
			  const tenantId = wx.getStorageSync('tenantId');
				const that = this;
				uni.showLoading({title:'图片上传中...'});
				uni.uploadFile({
						url: this.$baseUrl+`/worksite-admin/minio/upload?token=${token}&tenantId=${tenantId}&module=danger`, //从调用页面传入 -- url: 'http://127.0.0.1:3000/' 后端接口地址
						filePath: imgUrl, //从调用页面传入 --path: imgbox, 选取图片的地址数组  
						name: 'file', //文件名称可以自定义，要与后端配对使用：app.post('/',upload.single('img'),function(req,res,next)
						success: (resp) => {
							//图片上传成功，图片上传成功的变量+1
							const data = JSON.parse(resp.data);
							that.imgUrls.push(data.data.url);
							uni.hideLoading();
							console.log(resp.data) //在调试窗口显示后端返回的图片名称      
						},
						fail: (fail) => {  //失败
							uni.hideLoading();
							toast('上传失败','error')
							console.log('fail:' ,fail);
						},
						complete: (e) => { //不论成功、失败都执行		
							uni.hideLoading();
							console.log('执行完毕');
						}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
.image-list{
		gap: 10rpx;
		.img-l-item{
			position:relative;padding: 30rpx 24rpx 10rpx; border: 2rpx solid #D2D2D2;border-radius: 8rpx;
			.remove{position: absolute;right: 4rpx;top:4rpx;width:30rpx;height:30rpx;}
		}
		.img-item{width: 140rpx;height: 150rpx;border-radius: 12rpx;}
		.capture-con{
			text-align: center;font-size: 10px;font-weight: 500;color: #8B959F;
			width: 180rpx;height: 188rpx;border-radius: 10rpx;border: 2rpx dashed #D2D2D2;
			image{width: 40rpx;height: 36rpx;}
		}
	}
	
</style>
